package com.example.androidproject;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.widget.RadioButton;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import com.example.androidproject.databinding.ActivityRegisterBinding;
import com.example.androidproject.sqlite.UserRepository;

public class RegisterActivity extends AppCompatActivity {

   private ActivityRegisterBinding binding;
   private UserRepository userRepository;
   private String TAG = "RegisterActivity";

   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      binding = ActivityRegisterBinding.inflate(getLayoutInflater());
      setContentView(binding.getRoot());

      userRepository = new UserRepository(this);

      binding.registerButton.setOnClickListener(v -> registerUser());
   }

   private void registerUser() {
      String username = binding.usernameEditText.getText().toString().trim();
      String password = binding.passwordEditText.getText().toString().trim();
      String confirmPassword = binding.confirmPasswordEditText.getText().toString().trim();
      int selectedGenderId = binding.genderRadioGroup.getCheckedRadioButtonId();
      String gender = "";

      if (selectedGenderId != -1) {
         gender = ((RadioButton) findViewById(selectedGenderId)).getText().toString();
      }

      if (TextUtils.isEmpty(username) || TextUtils.isEmpty(password) || TextUtils.isEmpty(confirmPassword) || TextUtils.isEmpty(gender)) {
         Toast.makeText(this, "请填写所有字段", Toast.LENGTH_SHORT).show();
         return;
      }

      if (!password.equals(confirmPassword)) {
         Toast.makeText(this, "密码不一致", Toast.LENGTH_SHORT).show();
         return;
      }

      // 检查用户名是否已存在
      if (userRepository.isUsernameExists(username)) {
         Toast.makeText(this, "用户名已存在", Toast.LENGTH_SHORT).show();
         return;
      }

      userRepository.insertUser(username, password, gender);
      Toast.makeText(this, "注册成功", Toast.LENGTH_SHORT).show();
      Log.d(TAG, "registerUser: " + username + ":" + password + ":" + gender + ".");

      // 创建 Intent 并设置结果
      Intent resultIntent = new Intent();
      resultIntent.putExtra("username", username);
      resultIntent.putExtra("password", password);
      setResult(RESULT_OK, resultIntent); // 设置结果码和结果数据
      finish(); // 结束当前 Activity
   }
}

